package cn.flying.cloud.base.common.utils.jsch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

/**
 * jsch 工具类 操作sftp shell执行
 *
 * @author: admin
 * @date: 2025年04月27日 11:42
 * @version: 1.0
 */
public class JschUtil {
    private final Logger logger = LoggerFactory.getLogger(JschUtil.class);

    private final Session session;

    public JschUtil(String host, int port, String user, String password) throws JSchException {
        JSch jsch = new JSch();
        session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
    }

    /**
     * 上传文件
     */
    public void upload(String localFilePath, String remoteFilePath) throws JSchException, SftpException {
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        channel.put(localFilePath, remoteFilePath);
        logger.info("文件上传成功!");
        channel.disconnect();
    }

    /**
     * 下载文件
     */
    public void download(String remoteFilePath, String localFilePath) throws JSchException, SftpException {
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        channel.get(remoteFilePath, localFilePath);
        logger.info("文件下载成功!");

        channel.disconnect();
    }

    /**
     * 执行命令
     */
    public String command(String command) throws JSchException, IOException {
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);
        channel.setInputStream(null);
        channel.setErrStream(System.err);

        InputStream in = channel.getInputStream();
        channel.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }

        channel.disconnect();
        return output.toString();
    }

    public void disconnect() {
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }
}
